import { Collapse, Select, Switch, Avatar, Form, Input, message, Spin } from 'antd';
import React from 'react';
import './index.css';

import { useTranslation } from 'react-i18next';
import { useCallback, useContext, useEffect, useRef, useState } from 'react';
import Icon, { UserOutlined, GlobalOutlined, SettingOutlined, LogoutOutlined, RightSquareOutlined } from '@ant-design/icons';
import { ChatContext } from '@/app/chat-context';
import { STORAGE_LANG_KEY, STORAGE_THEME_KEY, STORAGE_USERINFO_KEY } from '@/utils/constants/index';
import { DarkSvg, SunnySvg } from '@/components/icons';
import Image from 'next/image';
import moment from 'moment';
import 'moment/locale/zh-cn';
import UploadModal from './components/uploadModal';
import { useRouter } from 'next/router';
import { cloneDeep } from 'lodash';
import { query_user_info, userUpdate, userUpdatePwd } from '@/client/api/login';
import { logoUrl } from '@/utils';

const enum FORM_FILED {
  PASS_WORD = 'password',
  USER_ID = 'userId',
}
type ModalType = 'edit' | 'add';


const userInfoSetting = () => {
  const { t, i18n } = useTranslation();
  const { mode, setMode, adminList, userInfo, handleUserInfoChange } = useContext(ChatContext);
  const router = useRouter();
  const { Panel } = Collapse;
  const validationRules = {
    'nick_name': {
      regex: /^[a-zA-Z\u4e00-\u9fa5\d_]+$/,
      errorMsg: t('nick_name')
    },
    'email': {
      regex: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
      errorMsg: t('email')
    },
    'telephone': {
      regex: /^1[3-9]\d{9}$/,
      errorMsg: t('telephone')
    }
  };
  const validateInput = (item: { filed: 'nick_name' | 'email' | 'telephone', value: string }) => {
    const rule = validationRules[item.filed];
    if (!item.value.trim()) {
      message.error(t('cannotBeEmpty'))
      return;
    }
    if (rule) {
      if (!rule.regex.test(item.value)) {
        message.error(rule.errorMsg);
        return;
      }
    }
    return true;
  }
  const onChange = (key: string | string[]) => {
    console.log(key);
  };
  const logOut = () => {
    localStorage.clear()
    sessionStorage.clear();
    router.push('/login')
  }
  const renderHeader = (type, title) => {

    let iconDom;
    if (type == 1) {
      iconDom = <UserOutlined />;
    } else if (type == 2) {
      iconDom = <GlobalOutlined />;
    } else if (type == 3) {
      iconDom = mode === 'dark' ? <Icon component={DarkSvg} /> : <Icon component={SunnySvg} />;
    } else if (type == 4) {
      iconDom = <LogoutOutlined />;
    }
    return (
      <div className="flex items-center gap-2">
        {iconDom}
        <span>{title}</span>
      </div>
    );
  }

  const handleToggleTheme = useCallback(() => {
    const theme = mode === 'light' ? 'dark' : 'light';
    setMode(theme);
    localStorage.setItem(STORAGE_THEME_KEY, theme);
  }, [mode, setMode]);

  const languageOptions = [
    { value: 'zh', label: t('Chinese') },
    { value: 'en', label: t('English') },
  ];
  const [i18nLanguage, setI18nLanguage] = useState(i18n.language);
  const handleChangeLang = useCallback(() => {
    const language = i18n.language === 'en' ? 'zh' : 'en';
    i18n.changeLanguage(language);
    if (language === 'zh') moment.locale('zh-cn');
    if (language === 'en') moment.locale('en');
    setI18nLanguage(language);
    localStorage.setItem(STORAGE_LANG_KEY, language);
  }, [i18n]);

  const onFinish = (values: any) => {
    console.log('Success:', values);
  };

  const onFinishFailed = (errorInfo: any) => {
    console.log('Failed:', errorInfo);
  };
  let initForm = [
    { filed: 'nick_name', value: '', title: t('Nickname'), type: 'input', isEdit: false, maxLength: 20 },
    { filed: FORM_FILED.USER_ID, value: '', title: t('AccountID'), type: 'input', isEdit: false, },
    { filed: 'email', value: '', title: t('Email'), type: 'input', isEdit: false, maxLength: 254, },
    { filed: 'telephone', value: '', title: t('Phone'), type: 'input', isEdit: false, maxLength: 11 },
    { filed: FORM_FILED.PASS_WORD, value: '', oldValue: '', title: t('Password'), type: 'input', isEdit: false, newPassword: '', confirmPassword: '', maxLength: 20 },
  ]
  const [loading, setLoading] = useState<any>(true);
  const queryUserInfoChange = () => {
    setLoading(true);
    query_user_info({}).then(res => {
      const data: any = res?.data?.data;
      if (data) {
        initForm = [
          { filed: 'nick_name', value: data?.nick_name || '', title: t('Nickname'), type: 'input', isEdit: false, maxLength: 20 },
          { filed: FORM_FILED.USER_ID, value: data?.login_name || '', title: t('AccountID'), type: 'input', isEdit: false, },
          { filed: 'email', value: data?.email || '', title: t('Email'), type: 'input', isEdit: false, maxLength: 254, },
          { filed: 'telephone', value: data?.telephone || '', title: t('Phone'), type: 'input', isEdit: false, maxLength: 11 },
          { filed: FORM_FILED.PASS_WORD, value: '', oldValue: '', title: t('Password'), type: 'input', isEdit: false, newPassword: '', confirmPassword: '', maxLength: 20 },
        ]

        const user = {
          ...userInfo,
          ...data,
        }
        handleUserInfoChange(JSON.stringify(user));
        setFormList(cloneDeep(initForm))
        setTempFormList(cloneDeep(initForm))
        setLoading(false);
      } else {
        message.error(userInfo?.data?.message || '查询失败!');
      }
    })
  }
  useEffect(() => {
    queryUserInfoChange();
  }, [i18n.language])
  const [formList, setFormList] = useState([] as any[]);

  const [tempFormList, setTempFormList] = useState([] as any[]);

  const formValueChange = (e: any, { index, key }: { index: number, key: 'value' | 'oldValue' | 'newPassword' | 'confirmPassword' }) => {

    const newFormList = cloneDeep(formList);
    newFormList[index][key] = e.target.value;
    setFormList(() => newFormList);
    handleUserInfoChange();
  }
  const passwordSave = async ({ item = {}, index }: { item: any, index: number }) => {
    const { oldValue, newPassword, confirmPassword } = item;
    if (!oldValue || !newPassword || !confirmPassword) {
      message.error('请输入完整信息!')
      return
    }
    if (newPassword !== confirmPassword) {
      message.error('两次密码不一致!')
      return
    }

    const params = {
      old_password: oldValue,
      new_password: newPassword,
      re_password: confirmPassword
    }
    const res = await userUpdatePwd(params);
    const data: any = res?.data?.data;
    if (data) {
      localStorage.clear();
      sessionStorage.clear();
      router.push('/login');
      message.success('修改成功!');
    } else {
      message.error(userInfo?.data?.message || '修改失败!');
    }
  }
  const clearFormItemChange = ({ index }: { index: number }) => {
    const newFormList = cloneDeep(formList);
    newFormList[index] = { ...tempFormList[index] };
    if (newFormList[index].filed == FORM_FILED.PASS_WORD) {
      newFormList[index].oldValue = '';
      newFormList[index].newPassword = '';
      newFormList[index].confirmPassword = '';
    }
    newFormList[index].isEdit = false;
    setFormList(() => newFormList);
  }

  const confirmEdit = async ({ item, index }: { item: any, index: number }) => {
    const newFormList = cloneDeep(formList);
    setFormList(() => newFormList);
    if (!validateInput(item)) return;

    const params = {
      ...userInfo,
      [item.filed]: item.value
    }
    const res = await userUpdate(params);
    const data: any = res?.data?.data;
    if (data) {
      newFormList[index].isEdit = false;
      queryUserInfoChange();
      message.success('修改成功!');
    } else {
      message.error(userInfo?.data?.message || '修改失败!');
    }
  };
  const formChange = () => {

    return <Form
      name="basic"
      labelAlign={'left'}
      labelCol={{ span: 6 }}
      wrapperCol={{ span: 16 }}
      initialValues={{ remember: true }}
      onFinish={onFinish}
      onFinishFailed={onFinishFailed}
      autoComplete="off"
    >
      {
        formList?.map((item, index) => {
          return <Form.Item
            label={item.title}
          >
            {
              item.isEdit ? <>
                {
                  <>
                    <div className='flex items-center  justify-between'>
                      {item.filed != FORM_FILED.PASS_WORD ?
                        <>
                          <Input maxLength={item.maxLength} defaultValue={item.value} onChange={(e) => formValueChange(e, { index, key: 'value' })} className='w-2/3' />
                          <div className='flex items-center gap-2'>
                            <div className='text-blue-500 cursor-pointer'
                              onClick={() => confirmEdit({ item, index })}>{t('verify')}</div>
                            <div className='cursor-pointer' onClick={() => clearFormItemChange({ index })}>{t('cancel')}</div>
                          </div>
                        </>
                        : '******'}
                    </div>
                  </>
                }
              </>
                : <div className='flex items-center justify-between'>
                  <div>{item.filed != FORM_FILED.PASS_WORD ? item.value : '******'}</div>
                  <div className='text-blue-500 cursor-pointer flex items-center gap-2'>
                    {
                      item.filed == FORM_FILED.USER_ID ?
                        '' :
                        <>
                          <div onClick={() => {
                            const newFormList = [...formList];
                            newFormList[index].isEdit = true;
                            setFormList(() => newFormList)
                          }}>{t('Edit')}</div>
                        </>
                    }
                  </div>
                </div>
            }
          </Form.Item>
        })
      }
      {
        formList.map((item, index) => {
          if (item.filed == FORM_FILED.PASS_WORD && item.isEdit) {
            return <>
              <Form.Item
                label={t('OldPassword')}
              >
                <Input maxLength={item.maxLength} defaultValue={item.oldValue} className='w-2/3' onChange={(e) => formValueChange(e, { index, key: 'oldValue' })} />
              </Form.Item>
              <Form.Item
                label={t('NewPassword')}
              >
                <Input maxLength={item.maxLength} defaultValue={item.newPassword} onChange={(e) => formValueChange(e, { index, key: 'newPassword' })}
                  className='w-2/3' />
              </Form.Item>
              <Form.Item
                label={t('ConfirmPassword')}
              >
                <div className='flex items-center justify-between'>
                  <Input maxLength={item.maxLength} defaultValue={item.confirmPassword} onChange={(e) => formValueChange(e, { index, key: 'confirmPassword' })}
                    className='w-2/3' />
                  <div className='flex items-center gap-2'>
                    <div className='text-blue-500 cursor-pointer' onClick={() => passwordSave({ item, index })}>{t('verify')}</div>
                    <div className='cursor-pointer' onClick={() => clearFormItemChange({ index })}>{t('cancel')}</div>
                  </div>
                </div>
              </Form.Item>
            </>

          }
        })
      }
    </Form>
  }

  const [modalType, setModalType] = useState<ModalType>('add');
  const [open, setOpen] = useState<boolean>(false);
  const handleCreate = () => {
    setModalType('add');
    setOpen(true);
  };
  return (
    <div className='w-full h-full flex flex-col justify-center items-center'>
      {
        loading ? <Spin className='mb-10' /> :
          <>
            <div className='flex items-center gap-7 w-1/3'>
              <div className="relative w-14 h-14 userAvatar " onClick={() => handleCreate()}>
                <Avatar size={64} icon={<Image
                  className='w-full h-full'
                  src={userInfo?.avatar_id ? logoUrl + userInfo.avatar_id : '/ai/user.png'}
                  alt="login"
                  width={20}
                  height={20}
                />} />
              </div>
              <div className='flex flex-col gap-2'>
                <div>{userInfo?.nick_name}</div>
                <div>用户名: {userInfo?.login_name}</div>
              </div>
            </div>
            <Collapse onChange={onChange} className='w-1/3 bg-bSet dark:bg-bSetDark mt-8' expandIconPosition='end' collapsible={'icon'} defaultActiveKey={['1']}>
              <Panel header={renderHeader('1', t('PersonalData'))} key="1">
                {formChange()}
              </Panel>
            </Collapse>

          </>
      }

      <Collapse onChange={onChange} className='w-1/3 bg-bSet dark:bg-bSetDark mt-3' expandIconPosition='end' collapsible={'icon'}>
        <Panel header={renderHeader('2', t('LanguageSettings'))} showArrow={false} key="2" extra={<Select
          value={i18nLanguage}
          style={{ width: 120 }}
          onChange={handleChangeLang}
          options={languageOptions}
        />}>
        </Panel>
      </Collapse>
      <Collapse onChange={onChange} className='w-1/3 bg-bSet dark:bg-bSetDark mt-3' expandIconPosition='end' collapsible={'icon'}>
        <Panel header={renderHeader('3', t('ThemeColors'))} showArrow={false} key="3" extra={<Switch
          defaultChecked={mode != 'dark' ? true : false} checkedChildren={t("LightColorMode")} unCheckedChildren={t("DarkMode")} onChange={handleToggleTheme} />}>
        </Panel>
      </Collapse>
      <Collapse className='w-1/3 bg-bSet dark:bg-bSetDark mt-3' expandIconPosition='end' collapsible={'icon'}>
        <Panel header={renderHeader('4', t('LogOut'))} showArrow={false} key="4" extra={<RightSquareOutlined onClick={logOut} className='cursor-pointer' />}>
        </Panel>
      </Collapse>
      {open && <UploadModal
        open={open}
        onCancel={() => {
          setOpen(false);
        }}
        refresh={() => { }}
        type={modalType} />}
    </div>
  );
}

export default userInfoSetting;
